<?php

header( 'Content-Type: text/plain' );

error_reporting( 0 );

function plural( $num ) {
	if ( $num != 1 )
		return 's';
}

function time_since( $date ) {
	$diff = time() - $date;
	if ( $diff == 0 )
		return 'Right now';
	if ( $diff < 60 )
		return $diff . ' second' . plural( $diff ) . ' ago';
	$diff = floor( $diff / 60 );
	if ( $diff < 60 )
		return $diff . ' minute' . plural( $diff ) . ' ago';
	$diff = floor( $diff / 60 );
	if ( $diff < 24 )
		return $diff . ' hour' . plural( $diff ) . ' ago';
	$diff = floor( $diff / 24 );
	if ( $diff < 7 )
		return $diff . ' day' . plural( $diff ) . ' ago';
	$diff = floor( $diff / 7 );
	if ( $diff < 4 )
		return $diff . ' week' . plural( $diff ) . ' ago';
	return 'on ' . date( 'F j<\\s\\u\\p>S</\\s\\u\\p>, Y', $date );
}

function clean_online_list( $room ) {
	$_members = file( dirname( __FILE__ ) . '/db/online/' . $room );
	$_members = array_filter( array_map( 'trim', $_members ) ); // Remove blank lines
	$members = array();
	foreach ( $_members as $member ) {
		if ( (int)substr( $member, 32 ) >= time() - 75 )
			$members[] = $member;
	}
	if ( $_members != $members )
		file_put_contents( dirname( __FILE__ ) . '/db/online/' . $room, implode( "\n", $members ) );
	return $members;
}

$_channels = glob( dirname( __FILE__ ) . '/db/chat/*.txt' );
$channels = array();

foreach ( $_channels as $channel ) {
	$channels[filesize( $channel ) > 1 ? filemtime( $channel ) : 0][] = array( substr( basename( $channel ), 0, -4 ), fileatime( $channel ), count( clean_online_list( basename( $channel ) ) ) );
}

krsort( $channels, SORT_NUMERIC );

$_channels = $channels;
$channels = array();

$i = 5;

foreach ( $_channels as $mtime => $_channel ) {
	foreach ( $_channel as $channel ) {
		if ( $i-- < 0 )
			break;
		$channels[] = $channel[0] . ':' . ( $mtime ? time_since( $mtime ) : 'Never' ) . ':' . time_since( $channel[1] ) . ':' . number_format( $channel[2] );
 	}
}

echo implode( "\n", $channels );

?>